<template>
  <div class="dashboard">
    <h2 class="page-title">系统概览</h2>
    
    <el-row :gutter="20">
      <el-col :span="8" v-if="!authStore.isAdmin">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>我的申请</span>
              <el-button type="primary" size="small" @click="goToCreateRequest">新建申请</el-button>
            </div>
          </template>
          <div class="card-content">
            <el-row>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ stats.pending }}</div>
                  <div class="stat-label status-pending">待审批</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ stats.approved }}</div>
                  <div class="stat-label status-approved">已通过</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-number">{{ stats.rejected }}</div>
                  <div class="stat-label status-rejected">已拒绝</div>
                </div>
              </el-col>
            </el-row>
            <div class="view-more">
              <el-button text type="primary" @click="goToRequestList">查看全部</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>通知提醒</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="markAllAsRead" 
                :disabled="!notificationStore.unreadCount"
              >
                全部已读
              </el-button>
            </div>
          </template>
          <div class="card-content">
            <div v-if="notifications.length > 0">
              <div 
                v-for="notification in notifications" 
                :key="notification.id" 
                class="notification-item"
                :class="{ 'unread': !notification.read }"
              >
                <div class="notification-title">
                  <el-icon v-if="!notification.read"><Bell /></el-icon>
                  {{ notification.title }}
                </div>
                <div class="notification-time">{{ formatDateTime(notification.createdAt) }}</div>
              </div>
              <div class="view-more">
                <el-button text type="primary" @click="goToNotifications">查看全部</el-button>
              </div>
            </div>
            <el-empty v-else description="暂无通知" />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8" v-if="authStore.isAdmin">
        <el-card class="dashboard-card">
          <template #header>
            <div class="card-header">
              <span>待审批申请</span>
              <el-button type="primary" size="small" @click="goToApprovals">查看全部</el-button>
            </div>
          </template>
          <div class="card-content">
            <div v-if="pendingRequests.length > 0">
              <div 
                v-for="request in pendingRequests" 
                :key="request.id" 
                class="request-item"
              >
                <div class="request-title">
                  {{ request.itemName }} × {{ request.quantity }}
                </div>
                <div class="request-info">
                  <span>申请人: {{ getUserName(request.requestUser) }}</span>
                  <span>{{ formatDateTime(request.createdAt, 'MM-DD HH:mm') }}</span>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无待审批申请" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Bell } from '@element-plus/icons-vue'
import { useAuthStore } from '@/store/auth'
import { useNotificationStore } from '@/store/notification'
import { getPurchaseRequests, getPendingPurchaseRequests } from '@/api/purchase-request'
import { getUnreadNotifications } from '@/api/notification'
import { formatDateTime } from '@/utils/format'

export default {
  name: 'Dashboard',
  setup() {
    const router = useRouter()
    const authStore = useAuthStore()
    const notificationStore = useNotificationStore()
    
    const stats = ref({
      pending: 0,
      approved: 0,
      rejected: 0
    })
    
    const notifications = ref([])
    const pendingRequests = ref([])
    
    // 获取用户名，处理可能的null或undefined情况
    const getUserName = (user) => {
      if (!user) return '未知用户'
      return user.name || user.username || '未知用户'
    }
    
    const fetchStats = async () => {
      try {
        // 获取各状态的申请数量
        const pendingRes = await getPurchaseRequests({ status: 'PENDING', page: 0, size: 1 })
        const approvedRes = await getPurchaseRequests({ status: 'APPROVED', page: 0, size: 1 })
        const rejectedRes = await getPurchaseRequests({ status: 'REJECTED', page: 0, size: 1 })
        
        stats.value = {
          pending: pendingRes?.totalElements || 0,
          approved: approvedRes?.totalElements || 0,
          rejected: rejectedRes?.totalElements || 0
        }
      } catch (error) {
        console.error('获取统计数据失败', error)
        stats.value = {
          pending: 0,
          approved: 0,
          rejected: 0
        }
      }
    }
    
    const fetchNotifications = async () => {
      try {
        const res = await getUnreadNotifications()
        notifications.value = Array.isArray(res) ? res.slice(0, 5) : [] // 只显示最新的5条
      } catch (error) {
        console.error('获取通知失败', error)
        notifications.value = []
      }
    }
    
    const fetchPendingRequests = async () => {
      if (!authStore.isAdmin) return
      
      try {
        const res = await getPendingPurchaseRequests({ page: 0, size: 5 })
        pendingRequests.value = res?.content || []
      } catch (error) {
        console.error('获取待审批申请失败', error)
        pendingRequests.value = []
      }
    }
    
    const markAllAsRead = async () => {
      await notificationStore.markAllAsRead()
      fetchNotifications()
    }
    
    const goToCreateRequest = () => {
      router.push({ name: 'CreatePurchaseRequest' })
    }
    
    const goToRequestList = () => {
      router.push({ name: 'PurchaseRequests' })
    }
    
    const goToNotifications = () => {
      router.push({ name: 'Notifications' })
    }
    
    const goToApprovals = () => {
      router.push({ name: 'Approvals' })
    }
    
    onMounted(() => {
      fetchStats()
      fetchNotifications()
      fetchPendingRequests()
    })
    
    return {
      authStore,
      notificationStore,
      stats,
      notifications,
      pendingRequests,
      formatDateTime,
      getUserName,
      markAllAsRead,
      goToCreateRequest,
      goToRequestList,
      goToNotifications,
      goToApprovals,
      Bell
    }
  }
}
</script>

<style scoped>
.dashboard-card {
  margin-bottom: 20px;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  min-height: 200px;
}

.stat-item {
  text-align: center;
  padding: 10px 0;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
}

.stat-label {
  font-size: 14px;
  margin-top: 5px;
}

.view-more {
  text-align: right;
  margin-top: 15px;
}

.notification-item {
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-title {
  font-size: 14px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.notification-title .el-icon {
  margin-right: 5px;
  color: #409EFF;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}

.request-item {
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.request-item:last-child {
  border-bottom: none;
}

.request-title {
  font-size: 14px;
  margin-bottom: 5px;
}

.request-info {
  font-size: 12px;
  color: #909399;
  display: flex;
  justify-content: space-between;
}
</style> 